package com.usian.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.article.feign.AppUserFeign;
import com.usian.article.feign.BehaviorFeign;
import com.usian.article.mapper.*;
import com.usian.article.service.ApArticleService;
import com.usian.model.article.dtos.ArticleHomeDto;
import com.usian.model.article.dtos.ArticleInfoDto;
import com.usian.model.article.pojos.*;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.behavior.pojos.ApLikesBehavior;
import com.usian.model.behavior.pojos.ApUnlikesBehavior;
import com.usian.model.common.constants.ArticleConstans;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserFollow;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import io.swagger.annotations.Authorization;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle>
        implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Value("${fastdfs.url}")
    private String fastServiceUrl;

    // 单页最大加载的文章数
    private final static short MAX_PAGE_SIZE = 50;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;


    @Override
    public ResponseResult load(ArticleHomeDto dto, Short loadtype) {
        // 1.参数校验
        if (StringUtils.isEmpty(dto.getTag())) {
            dto.setTag(ArticleConstans.DEFAULT_TAG);
        }

        if (dto.getSize() == null || dto.getSize().intValue() == 0) {
            // 默认取10条
            dto.setSize(10);
        }
        dto.setSize(Math.min(dto.getSize(), MAX_PAGE_SIZE));

        if (dto.getMinBehotTime() == null){
            dto.setMinBehotTime(new Date());
        }

        if (dto.getMaxBehotTime() == null){
            dto.setMaxBehotTime(new Date());
        }

        // 2.调用mapper去查询数据
        List<ApArticle> articleList = apArticleMapper.loadArticleList(dto, loadtype);
        // 3.返回数据
        ResponseResult responseResult = ResponseResult.okResult(articleList);

        responseResult.setHost(fastServiceUrl);

        return responseResult;
    }

    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        // 1.参数校验
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Map resultMap = new HashMap();
        //resultMap.put("config", )
        //resultMap.put("content", )
        // 2.分析一下查询哪张表
        // ap_article_config  ap_article_content
        // 3.调用api查询

        ApArticleConfig apArticleConfig =
                apArticleConfigMapper.selectOne(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, dto.getArticleId()));
        if (apArticleConfig == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (!apArticleConfig.getIsDown() && !apArticleConfig.getIsDelete()) {

            ApArticleContent content =
                    apArticleContentMapper.selectOne(
                            Wrappers.<ApArticleContent>lambdaQuery()
                                    .eq(ApArticleContent::getArticleId, dto.getArticleId()));
            resultMap.put("content", content);
        }
        resultMap.put("config", apArticleConfig);
        // 4.返回
        ResponseResult responseResult = ResponseResult.okResult(resultMap);
        responseResult.setHost(fastServiceUrl);
        return responseResult;
    }

    @Autowired
    private BehaviorFeign behaviorFeign;

    @Autowired
    private ApCollectionMapper apCollectionMapper;

    @Autowired
    private AppUserFeign appUserFeign;

    @Autowired
    private ApAuthorMapper apAuthorMapper;

    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        Map<String, Object> resultMap = new HashMap<>();
        boolean islike = false, isunlike = false, iscollection = false, isfollow = false;
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 查询实体id
        ApBehaviorEntry apBehaviorEntry =
                behaviorFeign.queryEntryByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        // 查询当前登录用户是否点赞
        ApLikesBehavior apLikesBehavior =
                behaviorFeign.queryLikesByEntryIdAndArticleId(apBehaviorEntry.getId(), dto.getArticleId(), ApLikesBehavior.Type.ARTICLE.getCode());
        if (apLikesBehavior != null && apLikesBehavior.getOperation() != null
                && apLikesBehavior.getOperation() == ApLikesBehavior.Operation.LIKE.getCode()) {
            islike = true;
        }
        // 查询当前登录用户是否不喜欢
        ApUnlikesBehavior apUnlikesBehavior = behaviorFeign.queryUnlikeByEntryIdAndArticleId(apBehaviorEntry.getId(), dto.getArticleId());
        if (apUnlikesBehavior != null && apUnlikesBehavior.getType() != null
                && apUnlikesBehavior.getType() == ApUnlikesBehavior.Type.UNLIKE.getCode()) {
            isunlike = true;
        }
        // 查询当前用户是否收藏过文章
        LambdaQueryWrapper<ApCollection> apCollectionLambdaQueryWrapper =
                Wrappers.<ApCollection>lambdaQuery().eq(ApCollection::getEntryId, apBehaviorEntry.getId()).eq(ApCollection::getArticleId, dto.getArticleId()).eq(ApCollection::getType, ApCollection.Type.ARTICLE);

        Integer collectCount =
                apCollectionMapper.selectCount(apCollectionLambdaQueryWrapper);
        if (collectCount == 1) {
            iscollection = true;
        }
        // 查询当前登录用户是否关注过该作者
        ApAuthor apAuthor = apAuthorMapper.selectById(dto.getAuthorId());
        ApUserFollow apUserFollow = appUserFeign.queryApUserFollowByUserIdAndFollowId(user.getId(), apAuthor.getUserId());
        if (apUserFollow != null) {
            isfollow = true;
        }

        resultMap.put("islike", islike);
        resultMap.put("isunlike", isunlike);
        resultMap.put("iscollection", iscollection);
        resultMap.put("isfollow", isfollow);
        return ResponseResult.okResult(resultMap);
    }
}
